package com.icomvn.game.pikachu.licence;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.Random;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.telephony.gsm.SmsManager;
import android.util.Log;

import com.icomvn.game.pikachu.config.Config;
import com.icomvn.game.pikachu.play.PlayPikachu;
import com.icomvn.game.pikachu.utility.MD5;
import com.icomvn.game.pikachu.utility.Parser;
import com.icomvn.game.pikachu.utility.Save;

public class Licence implements Runnable {
	String phoneNumberActiveGirl = Config.phoneNumberActiveGirl;
	String phoneNumberAward = Config.phoneNumberAward;
	String message = "";
	Activity activity = null;
	String queryAddrGirl = Config.queryAddrGirl;
	SharedPreferences setup;
	SharedPreferences.Editor editor;
	int level;
	ProgressDialog progress;
	// LevelPayScreen levelPay;
	String gameId = Config.gameId;
	String clientId;
	String keyGameActive = Config.keyGameActive;
	String keyGameAward = Config.keyGameAward;
	String erroMessage = "Vui lòng kiểm tra lại kết nối mạng GPRS hoặc Wifi";
	String titleErro = "Lỗi kết nối";
	boolean stop = false;
	String sessionId = "";
	String itemId = "";
	int mode = 0;
	PlayPikachu play;
	int sourceCall = 0;
	String contentId;
	String params[] = { "MAX_DOWNLOAD", "SHARE_ADDR", "SHARE_CODE",
			"UNLOCK_ADDR", "UNLOCK_CODE", "URL_DOWNLOAD", "URL_UPDATE" };
	String titleTag[] = { "<title>", "</title>" };
	String photoTag[] = { "<url>", "</url>" };

	public Licence(Activity activity, ProgressDialog progress, PlayPikachu play) {
		this.activity = activity;
		this.progress = progress;
		this.play = play;
		setup = activity.getSharedPreferences("pikachu_icom",
				Activity.MODE_PRIVATE);
		editor = setup.edit();
	}

	public void sendSMS(String phoneNumber, String message) {
		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, message, null, null);
	}

	public void SendSMSActiveGirl() {
		if ((clientId = setup.getString("clientid", "")).compareTo("") == 0) {
			clientId = UniqueClientID.getUniqueClientID();
			// xóa dòng này
			// clientId = "41433136353934323432303449";
			editor.putString("clientid", clientId);
			editor.commit();
		}
		level = Save.level + 1;
		itemId = String.valueOf(Save.girlCount + 1);
		sessionId = String.valueOf(new Date().getTime());
		// sessionId = "4416594242049";
		editor.putLong("sessionid" + String.valueOf(level), Long
				.valueOf(sessionId));
		editor.commit();
		message = keyGameActive + " " + clientId + " " + sessionId + " "
				+ itemId;
		Log.e("message", message);
		sendSMS(phoneNumberActiveGirl, message);
		try {
			Save.girlCount++;
			editor.putInt("girlcount", Save.girlCount);
			editor.commit();
		} catch (Exception e) {
		}
	}

	public void SendSMSAward(String phoneNumber) {
		message = keyGameAward + " " + phoneNumber;
		sendSMS(phoneNumberAward, message);
	}

	public void start(int mode, int level, int sourceCall) {
		stop = false;
		Save.start = false;
		Save.finish = false;
		this.mode = mode;
		Save.continueGame = false;
		this.sourceCall = sourceCall;
		if (level == -1)
			this.level = 2;
		else
			this.level = level;
		Thread t = new Thread(this);
		t.start();
	}


	public void run() {
		try {
			Save.finish = false;
			if ((clientId = setup.getString("clientid", "")).compareTo("") == 0) {
				clientId = UniqueClientID.getUniqueClientID();
				editor.putString("clientid", clientId);
				editor.commit();
			}
			if (mode == 1) {
				Random rand = new Random();
				String type = "2";
				String r = String.valueOf(rand.nextInt(10000));
				String a = MD5.toHex((r + type).getBytes());
				if (sessionId.compareTo("") == 0)
					sessionId = String.valueOf(setup.getLong("sessionid"
							+ String.valueOf(level), 0));
				itemId = String.valueOf(level);
				queryAddrGirl = queryAddrGirl + "&type=2&i=" + itemId
				+ "&c=" + clientId.toUpperCase() + "&s=" + sessionId.toUpperCase()
				+ "&a=" + a + "&r=" + r+"&size="+String.valueOf(Save.width)+"x"+String.valueOf(Save.heigth);
				Log.e("query", queryAddrGirl);
				for (int i = 0; i < 35; i++) {
					readInput();
					if (stop)
						break;
					try {
						Thread.sleep(2000);
					} catch (Exception e) {
						Log.e("e:", e.toString());
					}
				}
				Save.finish = stop;
				Save.downloadFinish[level] = stop;
				editor.putBoolean("downloadfinish" + String.valueOf(level),
						Save.downloadFinish[level]);
				editor.commit();
			}
			Save.start = true;
		} catch (Exception e) {
			e.toString();
		}
		try {
			updateNumberService();
		} catch (Exception e) {
			Log.e("erro", e.toString());
		}
	}

	public void readInput() {
		String result = "";
		try {
			// URL url = new URL(queryAddr + "?level=" + String.valueOf(level));
			URL url = new URL(queryAddrGirl);
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			http.setConnectTimeout(20000);
			if (http.getResponseCode() == HttpURLConnection.HTTP_OK) {
				Save.titleErro = "Ứng dụng đang được kích hoạt";
				Save.contentErro = "Ứng dụng của bạn đang được kích hoạt,vui lòng thử lại sau 5 phút";
				InputStream input = http.getInputStream();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(input));
				String readText = "";
				while ((readText = reader.readLine()) != null) {
					result += readText;
				}
				reader.close();
				// Log.e("xml content", "content:"+result);
				if (result.length() > 100) {
					// save to file
					String mid = Parser.getPropertyOnly(result, photoTag[0],
							photoTag[1]);
					Log.e("photo", mid);
					if (mid.length() > 10) {
						String name = "level" + String.valueOf(level) + ".jpg";
						if (mid.compareTo("") != 0)
							saveImage(mid.replace("&amp;", "&"), Save.path
									+ name);
						progress.setProgress(1);
						stop = true;
					}
					Save.titleErro = "Chúc mừng";
					Save.contentErro = "Bạn đã kích hoạt level mới thành công";
				}
			} else {
				Save.titleErro = "Bạn đã kích hoạt level mới thành công";
				Save.contentErro = "Không thể truy cập mạng,Vui lòng kiểm tra kết nối mạng GPRS hoặc Wifi";
			}
		} catch (Exception e) {
			Save.titleErro = "Lỗi";
			Save.contentErro = "Không thể truy cập mạng,Vui lòng kiểm tra kết nối mạng GPRS hoặc Wifi";
			Log.e("erro inputStream", e.toString());
		}
	}

	public void saveImage(String addr, String path) {
		try {
			URL url = new URL(addr);
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			http.setConnectTimeout(120000);
			if (http.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream is = http.getInputStream();
				// Bitmap mBitmap = BitmapFactory.decodeStream(is);
				File file = new File(path);
				FileOutputStream out = new FileOutputStream(file);
//				try {
//					IOUtils.copy(is, out);
//				} catch (Exception e1) {
//					out.close();
//					is.close();
//					Log.e("erro", e1.toString());
//				}
				// if (!mBitmap.compress(CompressFormat.PNG, 100, out))
				out.close();
				is.close();
			}

		} catch (Exception e) {
			Save.titleErro = "Lỗi";
			Save.contentErro = "Không thể truy cập mạng,Vui lòng kiểm tra kết nối mạng GPRS hoặc Wifi";
			Log.e("erro inputStream", e.toString());
		}
	}

	public void updateNumberService() {
		try {
			Log.e("print", "Đang tải thông tin...");
			URL url = new URL(Config.updateAddr);
			// Log.e("address:", Config.updateAddr);
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			http.setConnectTimeout(20000);
			if (http.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream input = http.getInputStream();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(input));
				String readText = "";
				String result = "";
				while ((readText = reader.readLine()) != null) {
					result += readText + ";";
				}
				result = result.replace(" ", ";");
				updateNumber(result);
				editor.putString("shareaddr", Config.phoneNumberAward);
				editor.putString("sharecode", Config.keyGameAward);
				editor.putString("unlockaddr", Config.phoneNumberActiveGirl);
				editor.putString("unlockcode", Config.keyGameActive);
				editor.putString("urldownload", Config.queryAddrGirl);
				editor.putString("urlupdate", Config.updateAddr);
				editor.commit();
			}
		} catch (Exception e) {
			Log.e("erro", e.toString());
		}
	}

	public void updateNumber(String result) {
		String parsered[] = result.split(";");
		try {
			for (int i = 0; i < parsered.length; i++) {
				String mid[] = parsered[i].split("=");
				try {
					if (mid[1].length() > 0)
						for (int j = 0; j < params.length; j++) {
							if (params[j].compareTo(mid[0]) == 0) {
								switch (j) {
								case 1:
									Config.phoneNumberAward = mid[1];
									break;
								case 2:
									Config.keyGameAward = mid[1];
									break;
								case 3:
									Config.phoneNumberActiveGirl = mid[1];
									break;
								case 4:
									Config.keyGameActive = mid[1];
									break;
								case 5:
									Config.queryAddrGirl = mid[1] + "="
											+ mid[2];
									break;
								case 6:
									Config.updateAddr = String.valueOf(mid[1])
											+ "=" + mid[2];
									break;
								}
								Log.e("content added", mid[1]);
								break;
							}
						}
				} catch (Exception e) {
				}
			}
		} catch (Exception e) {
			Log.e("erro", e.toString());
		}

	}

	public void stop() {
		this.stop = true;
	}
}
